package com.zhsm.fuxi.mvp.ui.activitys

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import com.alipay.sdk.app.PayTask
import com.hankkin.reading.base.BaseMvpActivity
import com.hankkin.reading.control.UserControl
import com.zhsm.fuxi.R
import com.zhsm.fuxi.app.Constant
import com.zhsm.fuxi.bean.PayOrderinfo
import com.zhsm.fuxi.bean.UserBean
import com.zhsm.fuxi.mvp.contract.AttMenuContract
import com.zhsm.fuxi.mvp.presenter.AttMenuPresenter
import com.zhsm.fuxi.mvp.ui.dialog.AttPayDialog
import com.zhsm.fuxi.mvp.ui.dialog.HintDialog
import com.zhsm.paipaiout.baselibrary.utils.ToastUtils
import kotlinx.android.synthetic.main.activity_att_menu.*
import kotlinx.android.synthetic.main.layout_head_bar.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.textColor
import java.lang.ref.WeakReference


/**
 * Created by GuZhC on 2018/11/05.
 * describe:
 */
class AttMenuActivity : BaseMvpActivity<AttMenuPresenter>(), AttMenuContract.IView {
    companion object {
        private val SDK_PAY_FLAG = 1
    }

    var isBtmPayMoney = true //是否是点击下面缴纳押金按钮进行的支付
    val mAttPayDialog by lazy { AttPayDialog(this) }
    val mHintDialog: HintDialog by lazy { HintDialog(this) }

    override fun getLayoutId(): Int { return R.layout.activity_att_menu }

    override fun registerPresenter() = AttMenuPresenter::class.java

    override fun initView() {
        setMiuiStatusBar()
        attMenuHeadBar.imgLift.onClick { finish() }
        attMenuHeadBar.tvTitle.text = "认证"
        attMenuTrueName.onClick {
            goTrueAtt()
        }
        UserControl.getCurrentUser()?.let {
            when (it.auth) {
                Constant.AttState.ATTSUCESS -> {
                    mycenterTvName.text = "已认证"
                }
                Constant.AttState.ATTING -> {
                    mycenterTvName.text = "认证中"
                }
                Constant.AttState.ATTNO -> {
                    mycenterTvName.text = "去认证"
                }
                Constant.AttState.ATTFAIL -> {
                    mycenterTvName.text = "认证失败"
                }
            }
            if (it.customerFreeze == Constant.FREEZE_MONEY.FREEZE) {
                mycenterTvEmail.text = "去解冻"
            } else {
                mycenterTvEmail.text = "去冻结"
            }
        }
        setisPayInfo()
        attMenuZhima.onClick {
            val userInfo = UserControl.getCurrentUser()
            if (userInfo?.auth == Constant.AttState.ATTSUCESS) {
                if (userInfo.customerFreeze == Constant.FREEZE_MONEY.UNFREEZE) {
                    showLoding()
                    isBtmPayMoney = false
                    getPresenter().getZhimaAuthPath()
                } else {
                    ToastUtils.makeText("押金解冻")
                }
            } else {
                hintShoudAtt()
            }
        }
    }

    override fun paySuccess(it: Int?) {
        if (isBtmPayMoney) {
            if (it == Constant.PAY_RES0ULT.PAING_SUCESS) {
                mAttPayDialog.paySucess()
                getPresenter().updaateUserIn()
            } else {
                hideLoding()
                ToastUtils.makeText("支付失败")
            }
        } else {
            if (it == 1) { //1代表冻结成功  其他失败
                mycenterTvEmail.text = "去解冻"
                getPresenter().updaateUserIn()
            } else {
                hideLoding()
                mycenterTvEmail.text = "去冻结"
                ToastUtils.makeText("支付失败")
            }
        }
    }

    override fun updaateUserInfoSuccess(userInfo: UserBean?) {
        hideLoding()
        userInfo?.let {
            UserControl.setCurrentUser(it)
            if (isBtmPayMoney) setisPayInfo()
        }
    }

    private fun hintShoudAtt() {
        mHintDialog.setOnClickAndRes("请先完成实名认证", R.drawable.att_out_hint, true, "去认证",
                object : HintDialog.onClickBtn {
                    override fun cancelBtn() {
                        mHintDialog.dismiss()
                    }

                    override fun sureBtn() {
                        goTrueAtt()
                        mHintDialog.dismiss()
                    }
                })
        mHintDialog.show()
    }

    private fun setisPayInfo() {
        UserControl.getCurrentUser()?.let {
            when (it.depositState) {
                Constant.MONEY.MONEY_FREEZE -> {
                    freezeHint.visibility = View.VISIBLE
                    addCashPledge.isEnabled = false
                    CashPledgeNum.text = it.depositAmount
                    CashPledgeNum.textColor = Color.parseColor("#B2B2C0")
                    attMenuMoney.background = resources.getDrawable(R.drawable.att_menu_bg_no)
                    addCashPledge.background = resources.getDrawable(R.drawable.shape_attbtn_freezemoney)
                    addCashPledge.text = "押金已冻结"
                }
                Constant.MONEY.MONEY_USABLE -> {
                    freezeHint.visibility = View.GONE
                    addCashPledge.isEnabled = true
                    CashPledgeNum.text = it.depositAmount
                    CashPledgeNum.textColor = resources.getColor(R.color.text_orange)
                    attMenuMoney.background = resources.getDrawable(R.drawable.att_menu_bg)
                    addCashPledge.background = resources.getDrawable(R.drawable.shape_attbtn_havemoney)
                    addCashPledge.text = "退押金"
                    addCashPledge.onClick {
                        mHintDialog.setOnClickAndRes("退还押金后将不能租车", R.drawable.att_backmoney_hint, true, "退押金",
                                object : HintDialog.onClickBtn {
                                    override fun cancelBtn() {
                                        mHintDialog.dismiss()
                                    }

                                    override fun sureBtn() {
                                        ToastUtils.makeText("退押金")
                                        mHintDialog.dismiss()
                                    }
                                })
                        mHintDialog.show()
                    }
                }
                Constant.MONEY.MONEY_BACK,
                Constant.MONEY.MONEY_NOHAVE -> {
                    freezeHint.visibility = View.GONE
                    addCashPledge.isEnabled = true
                    CashPledgeNum.text = "未缴纳押金"
                    CashPledgeNum.textColor = resources.getColor(R.color.text_orange)
                    attMenuMoney.background = resources.getDrawable(R.drawable.att_menu_bg)
                    addCashPledge.background = resources.getDrawable(R.drawable.shape_attbtn_nomoney)
                    addCashPledge.text = "缴纳押金"
                    addCashPledge.onClick {
                        if (UserControl.getCurrentUser()?.auth == Constant.AttState.ATTSUCESS) {
                            mAttPayDialog.show()
                        } else {
                            hintShoudAtt()
                        }
                    }
                    mAttPayDialog.onClickZfbPay = {
                        showLoding()
                        isBtmPayMoney = true
                        getPresenter().zfbPay()
                    }
                    mAttPayDialog.onClickWxPay = { ToastUtils.makeText("微信支付") }
                }
            }
        }
    }

    private fun goTrueAtt() {
        UserControl.getCurrentUser()?.let {
            when (it.auth) {
                Constant.AttState.ATTSUCESS -> {
                    ToastUtils.makeText("已认证")
                }
                Constant.AttState.ATTING -> {
                    startActivity(Intent(this@AttMenuActivity, AttIngActivity::class.java))
                }
                Constant.AttState.ATTNO -> {
                    startActivity(Intent(this@AttMenuActivity, AttActivity::class.java))
                }
                Constant.AttState.ATTFAIL -> {
                    startActivity(Intent(this@AttMenuActivity, AttFailedActivity::class.java))
                }
            }
        }
    }

    private val handler = MyHandler(this)
    //Kotlin中所有内部类默认是静态的（即嵌套类，不使用inner修饰）.而内部类（使用inner修饰），对象会隐式持有外部类的对象（跟java一样）
    class MyHandler(activity: AttMenuActivity) : Handler() {
        var weakReference = WeakReference(activity)
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    // 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                    weakReference.get()?.let {
                        if (it.isBtmPayMoney) it.getPresenter().alipayQuery(msg.data.getString("id"))
                        else it.getPresenter().freezeQuery(msg.data.getString("id"))
                    }
                }
            }
        }
    }

    override fun zfbPay(Orderinfo: PayOrderinfo?) {
        hideLoding()
        val payRunnable = Runnable {
            val alipay = PayTask(this@AttMenuActivity)
            val result = alipay.payV2(Orderinfo?.body, true)
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            val bundle = Bundle()
            bundle.putString("id",Orderinfo?.orderId)
            msg.data = bundle
            msg.obj = result
            handler.sendMessage(msg)
        }
        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }
}